You can send an Objective-C message to a C++ object that has been converted by a conversion operator ("a smart pointer"). In the following example, the C++ ptrSquare object aSquare is implicitly converted to the Objective-C type Square* using the conversion operator Square*() . The converted object receives the message calculateArea :
@interface Square {
id a;
}
...
@end
class ptrSquare {
Square* value;
public:
operator Square*();
};
square (ptrSquare aSquare) {
float z = [aSquare calculateArea]; // invokes operator Square*()
}
Due to the conversion, the compiler acts as if aSquare is statically typed to Square* in the message expression.
The above example uses only one conversion operator: operator Square* . You should avoid having multiple conversion operators in the same class that produce different pointer types--the compiler may choose the wrong conversion operator and not produce the desired type. If you need more than one conversion type, you must use an operator id conversion operator--the compiler chooses this over an operator converting to any other Objective-C class pointer type. If the class ptrSquare implemented other operator x *() conversions besides operator Square*() , it would also have to implement an operator id conversion so the compiler would know which conversion to look for.
Conversion operators allow you to implement so called "smart pointers" to Objective-C objects. Smart pointers are objects that act like pointers and perform some other action in addition whenever an object is accessed through them. For more information on smart pointers, see Bjarne Stroustrup's The C++ Programming Language, Second Edition (Addison-Wesley, 1991).